package com.cn.shuangzi.loginplugin.common.socialized.pay;


import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.loginplugin.common.socialized.ThirdPlatform;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

/**
 * Created by CN on 2017/3/17.
 */

public class WeChatPay {
    //    private String app_secret = "0ea4a78407f2148f63e06afa746a55bf";
    private IWXAPI iwxapi;
    private SZBaseActivity activity;
    private PayManager.OnPayListener onPayListener;
    private String orderInfo = "";   // 订单信息
    private JSONObject json;

    public WeChatPay(SZBaseActivity activity, String orderInfo, PayManager.OnPayListener onPayListener) {
        this.activity = activity;
        this.orderInfo = orderInfo;
        this.onPayListener = onPayListener;
        if (ThirdPlatform.WE_CHAT_APPID == null) {
            throw new IllegalArgumentException("wechat appid not init...");
        }
        iwxapi = WXAPIFactory.createWXAPI(activity, ThirdPlatform.WE_CHAT_APPID, true);
        iwxapi.registerApp(ThirdPlatform.WE_CHAT_APPID);
    }

    public void toPay() {
        try {
            json = new JSONObject(orderInfo);
            PayReq req = new PayReq();
            req.appId = ThirdPlatform.WE_CHAT_APPID;
            req.partnerId = json.getString("partnerid");
//            req.partnerId		= "1449152002";
            req.prepayId = json.getString("prepayid");
            req.nonceStr = json.getString("noncestr");
            req.timeStamp = json.getString("timestamp");
            req.packageValue = json.getString("package");
//            req.packageValue	= "Sign=WXPay";
            req.sign = json.getString("sign");
//            req.extData			= "app data"; // optional
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            if (!iwxapi.sendReq(req))
                onPayListener.onPayFailed();
        } catch (Exception e) {
            e.printStackTrace();
            onPayListener.onPayFailed();
        }
    }
}
